package felix.things.router.mqtt.server.broker.cluster;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.listener.ChannelTopic;
import org.springframework.data.redis.listener.RedisMessageListenerContainer;

@Configuration
public class RedisConfig {

    private final RedisConnectionFactory redisConnectionFactory;
    private RedisCluster redisCluster;

    private static final String CLUSTER_TOPIC = "mqtt-server:cluster";

    @Autowired
    public RedisConfig(RedisConnectionFactory redisConnectionFactory, RedisCluster redisCluster) {
        this.redisConnectionFactory = redisConnectionFactory;
        this.redisCluster = redisCluster;
    }

    /**
     * 将消息监听器绑定到消息容器
     */
    @Bean
    public RedisMessageListenerContainer messageListenerContainer() {
        RedisMessageListenerContainer container = new RedisMessageListenerContainer();
        container.setConnectionFactory(redisConnectionFactory);

        container.addMessageListener(redisCluster, new ChannelTopic(CLUSTER_TOPIC));
        return container;
    }
}